const http = require('http')
const https = require('https')
const cheerio = require('cheerio')
const path=require('path')
const fs=require('fs')

var pagePath=path.join(__dirname,'/index.html')

http.createServer((req, res) => {
    
    var movies = []
    if(req.url == '/'){
        var fileContent=fs.readFileSync(pagePath)
        res.writeHead(200,{'Content-Type':'text/html;charset:utf-8'})
        res.write(fileContent)
        res.end()
    }
    else if (req.url == '/getlist') {

        https.get("https://maoyan.com/films?showType=3", (r) => {
            var str = ''

            r.on('data', (chunk) => {
                str += chunk
            })

            r.on('end', () => {
                var $ = cheerio.load(str)

                $('dd').each((index, ele) => {
                    var divArr = $(ele).children('div')
                    var aArr = $(divArr[1]).children('a')
                    var movieId = $(aArr[0]).attr('data-val').split(':')[1].slice(0, -1)
                    var movieName = $(divArr[1]).children('a').text()
                    var iArr = $(divArr[2]).children('i')
                    var movieRange = $(iArr[0]).text() + $(iArr[1]).text() ? $(iArr[0]).text() + $(iArr[1]).text() : '暂无评分'

                    movies[index] = {
                        movieId: movieId,
                        movieName: movieName,
                        movieRange: movieRange
                    }
                })

                movieStr = JSON.stringify(movies)
            
                res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' })
                res.write(movieStr)
                res.end()
            })
        })


    }
}).listen(8081)

console.log('server')